package com.lj.back.manage.scaffold.module.sys.controller;

import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.ApiSupport;
import com.lj.back.manage.scaffold.common.DTO.LoginFail;
import com.lj.back.manage.scaffold.common.DTO.LoginResult;
import com.lj.back.manage.scaffold.common.DTO.LoginSuccess;
import com.lj.back.manage.scaffold.common.enums.ResponseEnum;
import com.lj.back.manage.scaffold.common.response.R;
import com.lj.back.manage.scaffold.common.util.Assert;
import com.lj.back.manage.scaffold.common.util.HttpRequestUtil;
import com.lj.back.manage.scaffold.module.sys.DTO.SysLoginDTO;
import com.lj.back.manage.scaffold.module.sys.service.SysLoginService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.data.util.CastUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * @author lv
 * @version 1.0.0
 */
@RestController
@RequestMapping("/sys")
@Api(tags = "后台管理---登录模块")
@ApiSupport(author = "lv")
@AllArgsConstructor
public class SysLoginController {

    private final SysLoginService sysLoginService;


    @PostMapping("/login")
    @ApiOperation(value = "登录")
    @ApiOperationSupport(order = 1)
    public R<Object> login(@RequestBody @Validated SysLoginDTO sysLoginDTO){
        LoginResult loginResult = sysLoginService.login(sysLoginDTO);
        if (loginResult instanceof LoginSuccess){
            return R.success(loginResult);
        }
        LoginFail loginFail = CastUtils.cast(loginResult);
        return R.build(loginFail.getResponse());
    }

    @PostMapping("/logout")
    @ApiOperation(value = "登出")
    @ApiOperationSupport(order = 2)
    public R<Object> logout(HttpServletRequest request){
        String token = HttpRequestUtil.getToken(request);
        Assert.assertNotNull(token, ResponseEnum.TOKEN_IS_NULL);
        return R.build(sysLoginService.logout(token));
    }
}
